package com.sky.service.impl;



import com.fasterxml.jackson.databind.util.BeanUtil;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressMapper;
import com.sky.service.AddressService;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class AddressServiceImpl implements AddressService {


    @Autowired
    private AddressMapper addressMapper;
    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void addAddress(AddressBook addressBook) {
        AddressBook address = new AddressBook();
        BeanUtils.copyProperties(addressBook,address);
        address.setUserId(BaseContext.getCurrentId());
        address.setIsDefault(0);

        // 插入数据
        addressMapper.insert(address);

    }

    /**
     * 查询地址列表
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressMapper.list(addressBook);
    }

    /**
     * 删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        AddressBook address = new AddressBook();
        address.setId(id);
        address.setUserId(BaseContext.getCurrentId());
        addressMapper.delete(address);
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    public void setDefault(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setUserId(BaseContext.getCurrentId());
        // 将所有的地址全部设置为false
        addressMapper.cancelDefaultAll(addressBook);
        // 设置对应的地址为默认地址
        addressMapper.setDefault(addressBook);
    }

    /**
     *修改地址
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        AddressBook address = new AddressBook();
        BeanUtils.copyProperties(addressBook,address);
        address.setIsDefault(0);
        address.setUserId(BaseContext.getCurrentId());
        addressMapper.update(address);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getDetail(Long id) {
        AddressBook addressBook = new AddressBook();
        addressBook.setId(id);
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressMapper.getDetail(addressBook);
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {

        return addressMapper.getDefault(BaseContext.getCurrentId());
    }
}
